<?php 
namespace app\admin\controller;

use app\common\model\admin\AdminMenu;
use think\Exception;
use app\common\model\admin\AdminLimit;
use think\Db;
use app\common\controller\Log;
use app\common\model\admin\AdminUser;
use think\Loader;
use app\common\model\admin\AdminLog;

class Manage extends Base
{
	/**
	 * 获取权限列表
	 * @return unknown
	 */
	public function limitList()
	{
		$list = AdminLimit::where(['state' => 1])->select()->toArray();
		return jsonSuccess($list);
	}
	/**
	 * 获取系统权限
	 * @return unknown
	 */
	public function getLimit()
	{
		//获取客户端传递的数据
		$data = $this->request->post('');
		//获取全部权限
		$all_limit = AdminMenu::where(['parent_id' => ['neq',0],'state' => 1])->field('id,menu_name')->select()->toArray();
		foreach ($all_limit as &$rows) {
			$rows['key'] = $rows['id'];
			$rows['label'] = $rows['menu_name'];
		}
		$real = [];
		$name = '';
		if($data['id'] > 0) {
			$limit = AdminLimit::get($data['id']);
			$real = json_decode($limit->limit_data,true);
			$name = $limit->limit_name;
		}
		return jsonSuccess([
				'all' => $all_limit,
				'real' => $real,
				'name' => $name
		]);
	}
	
	/**
	 * 权限操作
	 * @throws Exception
	 * @return unknown
	 */
	public function limitSet()
	{
		//获取客户端传递的数据
		$data = $this->request->post('');
		$id = $data['id'];
		$info = $data['data'];
		Db::startTrans();
		try {
			if(!$info['limit_name'])throw new Exception('请输入权限名称');
			if(!count($info['limit_data']))throw new Exception('请选择权限');
			$info['limit_data'] = json_encode($info['limit_data']);
			//添加权限
			if(!$id) {
				$info['create_time'] = time();
				$info['update_time'] = time();
				AdminLimit::create($info);
				Log::addLog(1, '添加权限【'.$info['limit_name'].'】');
			}else{
				if($id == 1)throw new Exception('非法操作');
				$info['update_time'] = time();
				AdminLimit::where(['id' => $id])->update($info);
				Log::addLog(2, '修改权限【'.$info['limit_name'].'】');
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}

	
	/**
	 * 删除权限
	 * @throws Exception
	 * @return unknown
	 */
	public function deleteLimit()
	{
		//获取客户端传递的数据
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$limit = AdminLimit::get($id);
			if(!$limit->state)throw new Exception('状态错误');
			if(AdminUser::where(['admin_limit' => $id , 'admin_state' => 1])->value('id'))
				throw new Exception('该权限正在被管理员使用，不可删除');
			$limit->save(['state' => 0]);
			Log::addLog(3, "删除权限【{$limit->limit_name}】");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('删除成功');
	}

	/**
	 * 添加修改管理员
	 * @throws Exception
	 * @return unknown
	 */
	public function manageSet()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			$data['update_time'] = time();
			if(empty($data['id'])) {    //添加管理员
				//验证数据合法性
				$validate = Loader::validate('Manage');
				if(!$validate->scene('add') -> check($data))throw new Exception($validate->getError());
				if(AdminUser::where(['admin_name' => $data['admin_name']])->value('id'))
					throw new Exception('该管理员账号已存在');
				if($data['admin_limit'] == 1 && AdminUser::where(['admin_limit' => 1])->value('id'))
					throw new Exception('超级管理员只能有一个');
				$data['admin_pwd'] = md5($data['admin_pwd']);
				$data['create_time'] = time();
				AdminUser::create($data);
				//添加日志
				Log::addLog(1, '添加管理员【'.$data['admin_real'].'】');
			}else{
				$pwd_len = strlen($data['admin_pwd']);
				if($pwd_len > 20){
					unset($data['admin_pwd']);
				}else{
					if($pwd_len < 6 || $pwd_len > 10)throw new Exception('密码在6-10位之间的数字字母组合');
					$data['admin_pwd'] = md5($data['admin_pwd']);
				}
				//验证数据合法性
				$validate = Loader::validate('Manage');
				if(!$validate->scene('update') -> check($data))throw new Exception($validate->getError());
				AdminUser::where(['id' => $data['id']])->update($data);
				//添加日志
				Log::addLog(2, '修改管理员【'.$data['admin_real'].'】');
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}

	/**
	 * 管理员列表
	 * @return unknown
	 */
	public function manageList()
	{
		$data = $this->request->post('');
		if(!empty($data['manage'])) {
			$manage = $data['manage'];
			$list = AdminUser::where(['admin_state' => ['neq',2],'admin_name' => ['like',"%{$manage}%"]])->select()->toArray();
			if(!$list)$list = AdminUser::where(['admin_state' => ['neq',2],'admin_real' => ['like',"%{$manage}%"]])->select()->toArray();
		}else{
			$list = AdminUser::where(['admin_state' => ['neq',2]])->select()->toArray();
		}
		
		return jsonSuccess($list);
	}
	
	/**
	 * 更改管理员状态
	 * @throws Exception
	 * @return unknown
	 */
	public function setState()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			$admin_user = AdminUser::get($data['id']);
			if($admin_user -> admin_limit['id'] == 1)throw new Exception('超级管理员无法停用');
			if($admin_user['admin_state'] != $data['state'])throw new Exception('状态错误');
			$state = $data['state'] == 1 ? 0 : 1;
			//提交修改
			$admin_user -> save(['admin_state' => $state,'update_time' => time()]);
			$state ? Log::addLog(2, '启用管理员【'.$admin_user->admin_real.'】') : Log::addLog(2, '停用管理员【'.$admin_user->admin_real.'】');
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}
	
	/**
	 * 获取管理员信息
	 * @return unknown
	 */
	public function getManage()
	{
		//获取客户端传递的数据
		$id = $this->request->post('id');
		$info = AdminUser::where(['id' => $id])->field('id,admin_name,admin_real,admin_pwd,admin_limit,admin_mobile')->find() -> toArray();
		$info['admin_limit'] = $info['admin_limit']['id'];
		return jsonSuccess($info);
	}
	
	/**
	 * 批量停用
	 */
	public function batchStop()
	{
		$data = $this->request->post('');
		$id_arr = $data['id'];
		Db::startTrans();
		try {
			$admin_names = AdminUser::where(['id' => ['in',$id_arr],'admin_limit' => ['neq',1]])->column('admin_real');
			//停用
			AdminUser::where(['id' => ['in',$id_arr],'admin_limit' => ['neq',1]])->update(['admin_state' => 0,'update_time' => time()]);
			//添加日志
			foreach ($admin_names as $row) {
				Log::addLog(2, '停用管理员【'.$row.'】');
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('批量停用成功');
	}

	/**
	 * 获取后台操作日志列表
	 * @return unknown
	 */
	public function logList()
	{
		$data = $this->request->post('');
		//初始化查询条件
		$where = [];
		//管理员姓名模糊查询
		if(!empty($data['manage'])) {
			$manage = $data['manage'];
			$admin_id = AdminUser::where(['admin_real' => ['like',"%{$manage}%"]])->column('id');
			$where['admin_id'] = ['in',$admin_id];
		}
		//操作状态查询
		if(!empty($data['style'])) {
			$where['style'] = $data['style'];
		}
		//dump($data['times']);
		//时间查询
		if(is_array($data['times']) && count($data['times']) == 2 ){
			$start_time = strtotime($data['times'][0]);
			$end_time = strtotime($data['times'][1]);
			$where['create_time'] = ['between',[$start_time,$end_time]];
		}
		$list = AdminLog::where($where)->order('id desc')->paginate()->toArray();
		return jsonSuccess($list);
	}

	
}